import { defineStore } from 'pinia';
import { Contact } from '../../types';
import StorageManager from '../../utils/storage';
import { nanoid } from '@/utils/nanoid-polyfill';

interface ContactState {
  contacts: Contact[];
  loading: boolean;
  error: string | null;
}

export const useContactStore = defineStore('contact', {
  state: (): ContactState => ({
    contacts: [],
    loading: false,
    error: null
  }),

  getters: {
    // 获取所有联系人
    getAllContacts: (state) => state.contacts,
    
    // 按分类获取联系人
    getContactsByCategory: (state) => (category: string) => {
      return state.contacts.filter(contact => contact.category === category);
    },
    
    // 获取联系人详情
    getContactById: (state) => (id: string) => {
      return state.contacts.find(contact => contact.id === id);
    }
  },

  actions: {
    // 加载联系人列表
    async loadContacts() {
      this.loading = true;
      this.error = null;
      try {
        this.contacts = await StorageManager.getContacts();
      } catch (error) {
        this.error = '加载联系人失败';
        console.error('加载联系人失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 添加联系人
    async addContact(contact: Omit<Contact, 'id' | 'createTime' | 'updateTime'>) {
      this.loading = true;
      this.error = null;
      try {
        const newContact: Contact = {
          ...contact,
          id: nanoid(),
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveContact(newContact);
        this.contacts.push(newContact);
        return newContact.id;
      } catch (error) {
        this.error = '添加联系人失败';
        console.error('添加联系人失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新联系人
    async updateContact(contact: Contact) {
      this.loading = true;
      this.error = null;
      try {
        const updatedContact = {
          ...contact,
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveContact(updatedContact);
        const index = this.contacts.findIndex(c => c.id === contact.id);
        if (index > -1) {
          this.contacts[index] = updatedContact;
        }
      } catch (error) {
        this.error = '更新联系人失败';
        console.error('更新联系人失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除联系人
    async deleteContact(id: string) {
      this.loading = true;
      this.error = null;
      try {
        await StorageManager.deleteContact(id);
        this.contacts = this.contacts.filter(contact => contact.id !== id);
      } catch (error) {
        this.error = '删除联系人失败';
        console.error('删除联系人失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清空联系人列表
    async clearContacts() {
      this.loading = true;
      this.error = null;
      try {
        for (const contact of this.contacts) {
          await StorageManager.deleteContact(contact.id);
        }
        this.contacts = [];
      } catch (error) {
        this.error = '清空联系人失败';
        console.error('清空联系人失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    }
  },

  persist: true
}); 